package middleware

import (
	"github.com/gin-gonic/gin"
	"myserver/model"
	"myserver/response"
	"myserver/tool"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(context *gin.Context) {

		//获取authorization header
		tokenString := context.GetHeader("Authorization")
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			response.Failed(context, gin.H{
				"code": "500",
				"msg":  "权限不足",
			})
			context.Abort()
		}

		//把常规tokenString的字符串拿去解析。是去掉"Bearer "后的字符串
		tokenString = tokenString[7:]
		token, claims, err := tool.ParseToken(tokenString)
		if err != nil || !token.Valid {
			response.Failed(context, gin.H{
				"code": "401",
				"msg":  "权限不足",
			})
			context.Abort()
			return
		}

		//验证通过后获取claim 中的userId
		userId := claims.UserId
		DB := tool.GetDB()
		var user model.User
		DB.Db.First(&user, userId)

		//用户
		if user.ID == 0 {
			response.Failed(context, gin.H{
				"code": "401",
				"msg":  "权限不足",
			})
			context.Abort()
			return
		}

		//用户存在 将user的信息写入到上下文
		context.Set("user", user)
		context.Next()
	}
}
